package xyz.zyl2020.controller;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.zyl2020.entity.User;
import xyz.zyl2020.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author ZhuYinglong
 * @date 2020/9/2 0002
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public String login(String username, String password, HttpSession session) {
        User user = userService.getUserByUsernameAndPassword(username, password);
        String userJson = JSONObject.toJSONString(user);
        session.setAttribute("user", userJson);
        log.info("sessionId: {}, user: {}", session.getId(), userJson);
        return JSONObject.toJSONString(user);
    }

    @GetMapping("/data")
    public String getData(HttpSession session) {
        Object user = session.getAttribute("user");
        String userJson = JSONObject.toJSONString(user);
        log.info("sessionId: {}, user: {}", session.getId(), userJson);
        return userJson;
    }
}
